
import Pure from 'pure-frontend';

/* SOURCE-CODE-START */

"use strict";

Pure.app.viewMain('example2-edit', function (scope, view) {
  var urlParams = view.getUrlParams();
  var model = view.getDataModel();

  var queryParams = {
    id: urlParams.id
  };

  view.callService('api/example/getDetail', queryParams)
    .waitResult(function (result, textStatus, jqXHR) {
      model.setData('*', result.data);

      uiUtils.view.setCurrentFormDataToContext(scope, getFormData);
    });

  // 定义校验规则
  view.$find('form').validate({
    rules: {
      exampleName: 'required'
    },
    messages: {
      exampleName: '${t("ui.example.example2.validation.inputExampleName")}'
    }
  });

  // 点击返回按钮的事件
  view.$ui('backBtn').on('click', function () {
    Pure.app.popView('app/example2/search');
  });

  // 点击保存按钮的事件
  view.$ui('saveBtn').on('click', function () {
    var checkResult = view.$find('form').valid();
    if (!checkResult) {
      return;
    }

    var upDateData = model.getData('*');

    view.callService('api/example/updateDetail', upDateData)
      .waitResult(function (result, textStatus, jqXHR) {
        if (result.success) {
          Pure.app.showMessage('${t("ui.system.common.msg.saveSuccess")}');
          model.setData('*', result.data);

          uiUtils.view.setCurrentFormDataToContext(scope, getFormData);
        } else {
          Pure.app.showError(result.message);
        }
      });
  });

  // 离开时检查表单数据是否未保存
  uiUtils.view.checkFormDataChangeWhenLeave(scope, getFormData);

  function getFormData() {
    return model.getData('*');
  }

});

/* SOURCE-CODE-END */
